package com.example.serviceandroidjava;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import com.example.serviceandroidjava.bindServiceBinder.LocalService;

public class MainActivity extends AppCompatActivity {
    LocalService mService;
    boolean mBound = false;
    private Button btn;

    @Override
    protected void onStart() {
        super.onStart();
        //绑定服务
        Intent intent = new Intent(this, LocalService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        //解绑服务
        unbindService(connection);
        mBound = false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //启动服务
//      Intent intent = new Intent(this, HelloService.class);
//      startService(intent);

        //启动前台服务
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            Intent intent = new Intent(this, ForegroundService.class);
//            startService(intent);
//            Context context = getApplicationContext();
//            context.startForegroundService(intent);
//        } else {
//            Log.i("MainActivity", "版本问题");
//        }

        //点击获取随机数字（绑定服务）
        btn = findViewById(R.id.button);
        btn.setOnClickListener(view -> {
            if (mBound) {
                int number = mService.getRandomNumber();
                Toast.makeText(this, "number: " + number, Toast.LENGTH_LONG).show();
            } else {
                Log.i("MainActivity", "未绑定上");
            }
        });
    }

    private final ServiceConnection connection = new ServiceConnection() {
        //连接服务
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            LocalService.LocalBinder binder = (LocalService.LocalBinder) iBinder;
            mService = binder.getService();
            mBound = true;
        }

        //断开服务
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBound = false;
        }
    };

    private final ServiceConnection myServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            //系统调用该方法以传递服务的onBind()方法所返回的IBinder
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            //当与服务连接意外中断时，例如服务崩溃或被终止时
            //取消绑定不会调用
        }
    };
}

